package com.example.xinwenkehuduan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.gdcp.Demo.Data;
import cn.gdcp.Demo.UserLike;
import cn.gdcp.FragmentAdapter.NewsAdapter;

public class LikeActivity extends AppCompatActivity {
    private RecyclerView rvLike;
    private NewsAdapter adapter;
    private List<Data> dataList = new ArrayList<>();
    private LikeRecevier recevier;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_like);
        setTitle("我的收藏");

        rvLike = findViewById(R.id.rv_like);
        rvLike.setLayoutManager(new LinearLayoutManager(LikeActivity.this));
        adapter = new NewsAdapter(dataList);
        rvLike.setAdapter(adapter);

        getNewsDataList();

        recevier = new LikeRecevier();
        IntentFilter filter = new IntentFilter();
        filter.addAction("LIKE_CHANGED");
        registerReceiver(recevier,filter);
        
        

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(recevier);
    }

    private void getNewsDataList() {
        String userid = BmobUser.getCurrentUser(BmobUser.class).getObjectId();
        BmobQuery<UserLike> userLikeBmobQuery = new BmobQuery<>();
        userLikeBmobQuery.addWhereEqualTo("userID",userid);
        userLikeBmobQuery.addWhereEqualTo("isLike",true);

        userLikeBmobQuery.findObjects(new FindListener<UserLike>() {
            @Override
            public void done(List<UserLike> list, BmobException e) {
                if (e==null){
                    dataList.clear();



                    if (list!=null && list.size()>0){
                        for(UserLike userLike : list){
                            String newsjson = userLike.getNewsJSON();
                            Data data = new Gson().fromJson(newsjson,Data.class);
                            dataList.add(data);
                        }


                    }
                    adapter.changeDate(dataList);
                }

            }
        });

    }

    class LikeRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            getNewsDataList();
        }
    }
}




